package main

import (
	"crypto/sha512"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

type BaseModel struct {
	ID        int32          `gorm:"primarykey;type:int comment 'ID'" json:"id"`
	CreatedAt time.Time      `gorm:"column:add_time;type:datetime comment '创建时间'" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:update_time;type:datetime comment '更新时间'" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"type:datetime comment '删除时间'" json:"deleted_at"`
	IsDeleted bool
}

/*
1. 密文
 1. 对称加密
 2. 非对称加密
 3. md5 信息摘要算法
2. 密文不可反解
 密码如果不可反解, 用户找回密码
*/

type User struct {
	BaseModel
	Mobile   string     `gorm:"index:idx_mobile;unique;type:varchar(11) comment '手机号';not null" json:"mobile"`
	Password string     `gorm:"type:varchar(100) comment '密码';not null" json:"password"`
	NickName string     `gorm:"type:varchar(20) comment '用户名'" json:"nick_name"`
	Birthday *time.Time `gorm:"type:datetime comment '生日'" json:"birthday"`
	Gender   string     `gorm:"column:gender;default:male;type:varchar(6) comment 'female 表示女, male 表示男'" json:"gender"`
	Role     int        `gorm:"column:role;default:1; type:int comment '1 表示普通用户, 2 表示管理员'" json:"role"`
}

func main() {
	dsn := "root:56248123@tcp(192.168.16.107:3306)/mxshop_user_srv?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		},
	)

	// 全局模式
	var err error
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁止表名复数形式, 例如User的表名默认是users
		},
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(&User{})

	options := &password.Options{10, 100, 32, sha512.New}
	salt, encodedPwd := password.Encode("56248123", options)
	newPassword := fmt.Sprintf("$pbkdf2-sha512$%s$%s", salt, encodedPwd)

	for i := 0; i < 10; i++ {
		user := User{
			NickName: fmt.Sprintf("czc%d", i),
			Mobile:   fmt.Sprintf("1306735369%d", i),
			Password: newPassword,
		}
		db.Save(&user)
	}
}
